use loco_rs::prelude::*;
use serde::{Deserialize, Serialize};
use uuid::Uuid;

pub use super::_entities::attribute_groups::{self, ActiveModel, Entity, Model};

#[derive(Debug, Deserialize, Serialize)]
pub struct CreateParams {
    pub position: i32,
}

#[derive(Debug, Validate, Deserialize)]
pub struct Validator {}

impl Validatable for ActiveModel {
    fn validator(&self) -> Box<dyn Validate> {
        Box::new(Validator {})
    }
}

#[async_trait::async_trait]
impl ActiveModelBehavior for ActiveModel {
    async fn before_save<C>(self, _db: &C, insert: bool) -> Result<Self, DbErr>
    where
        C: ConnectionTrait,
    {
        self.validate()?;
        if insert {
            let mut this = self;
            this.id = ActiveValue::Set(Uuid::new_v4().to_string());
            Ok(this)
        } else {
            Ok(self)
        }
    }
}

impl Model {
    /// finds an attribute group by the provided id
    ///
    /// # Errors
    ///
    /// When could not find attribute group or DB query error
    pub async fn find_by_id(db: &DatabaseConnection, id: &str) -> ModelResult<Self> {
        let attribute_group = attribute_groups::Entity::find()
            .filter(
                query::condition()
                    .eq(attribute_groups::Column::Id, id)
                    .build(),
            )
            .one(db)
            .await?;
        attribute_group.ok_or_else(|| ModelError::EntityNotFound)
    }

    pub async fn find_by_position(db: &DatabaseConnection, position: i32) -> ModelResult<Vec<Self>> {
        let attribute_group = attribute_groups::Entity::find()
            .filter(
                query::condition()
                    .eq(attribute_groups::Column::Position, position)
                    .build(),
            )
            .all(db)
            .await?;
        Ok(attribute_group)
    }

    /// Asynchronously creates an attribute group and saves it to the database.
    ///
    /// # Errors
    ///
    /// When could not save the attribute group into the DB
    pub async fn create(db: &DatabaseConnection, params: &CreateParams) -> ModelResult<Self> {
        let txn = db.begin().await?;

        let attribute_group = ActiveModel {
            position: ActiveValue::set(params.position),
            ..Default::default()
        }
        .insert(&txn)
        .await?;

        txn.commit().await?;

        Ok(attribute_group)
    }
}

impl ActiveModel {
    /// Updates the attribute group's position
    ///
    /// # Errors
    ///
    /// when has DB query error
    pub async fn update_position(
        mut self,
        db: &DatabaseConnection,
        position: i32,
    ) -> ModelResult<Model> {
        self.position = ActiveValue::set(position);
        Ok(self.update(db).await?)
    }
}
